﻿using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinApp.i18n;
using WinApp.Until;
using WinApp.ViewModel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace WinApp.View
{
    public partial class ExamPlay : UserControl
    {
        //WebBrowser _webBrowserLms;  貌似是ie内核不支持
        private Microsoft.Web.WebView2.WinForms.WebView2 _webView2;
        public WinApp _parent { get; set; }
        public TagExamsSessionDto _inputDto { get; set; }
        public ExamPlay()
        {
            InitializeComponent();

            // 创建WebView2实例
            _webView2 = new Microsoft.Web.WebView2.WinForms.WebView2();
            // 设置Dock样式为Fill，使其填充整个窗体或指定的Panel等控件
            _webView2.Dock = DockStyle.Fill;
            this.panel2.Controls.Add(_webView2);
            // 初始化WebView2环境
            InitializeAsync();
        }

        private async void InitializeAsync()
        {
            // 确保CoreWebView2运行时已准备就绪
            await _webView2.EnsureCoreWebView2Async();
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            _webView2.Source = new Uri("about:blank");
            _parent.CloseExamPlay();
        }

        private void ExamPlay_Load(object sender, EventArgs e)
        {
            _webView2.CoreWebView2.NavigationStarting += async (sender, args) =>
            {
                var token = string.IsNullOrWhiteSpace(WebApiHelper._Authorization) ? "" : WebApiHelper._Authorization;
                Dictionary<string, string> tokenDic = new Dictionary<string, string>();
                tokenDic.Add("token", token);

                string jsString1 = string.Format("sessionStorage.setItem('refresh_token', '{0}')", WebApiHelper._RefreshToken);
                await _webView2.CoreWebView2.ExecuteScriptAsync(jsString1);

                string jsString = string.Format("sessionStorage.setItem('_token', '{0}')", JsonConvert.SerializeObject(tokenDic));
                await _webView2.CoreWebView2.ExecuteScriptAsync(jsString);
            };
        }

        public void LoadExamPlay()
        {
            if (_webView2 == null || _webView2.CoreWebView2 == null)
            {
                UIMessageDialog.ShowMessageDialog(Language.GetLang("notFindWebView"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                return;
            }

            var host = GlobalVariables.HostIp;
            var webIp = GlobalVariables.WebIp;
            var langType = GlobalVariables.SystemLanguage == LanguageType.English ? "en-US" : "zh-CN";

            //string baiduUrl = "https://www.baidu.com";
            string playerUrl = webIp + "player/";

            var cookieManager = _webView2.CoreWebView2.CookieManager;
            var jsonItem = JsonConvert.SerializeObject(_inputDto);
            CoreWebView2Cookie cookie1 = cookieManager.CreateCookie("myExamination", jsonItem, GlobalVariables.RootDomainName, "/");
            cookie1.SameSite = CoreWebView2CookieSameSiteKind.Lax;
            cookieManager.AddOrUpdateCookie(cookie1);

            _webView2.CoreWebView2.Navigate(playerUrl);
        }
    }
}
